<?php
/**
 * Created by PhpStorm.
 * User: xuanqiang
 * Date: 2018/2/6
 * Time: 23:02
 */

namespace app\wechat\controller;

use app\lib\exception\WeChatException;
use think\Controller;
use think\Exception;
use think\Session;
use think\Config;


class BaseToken extends Controller
{
    protected $wxAppID;
    protected $wxAppSecret;
    protected $wxAccessTokenUrl;
    protected $wxBaseUrl;

    public function __construct()
    {
        parent::__construct();
        $this->wxAppID = config('wx.app_id');
        $this->wxAppSecret = config('wx.app_secret');
        $this->wxAccessTokenUrl = sprintf('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s',$this->wxAppID,$this->wxAppSecret);
    }

    /**
     * 将access_token存储到session中
     */
    public function getWxAccessToken(){
        $access_token = cache('access_token');
        if(!$access_token){
            //调取接口获取
            $path = $this->wxAccessTokenUrl;
            $wxResult = $this->send($path);
            $access_token = $wxResult['access_token'];
            cache('access_token',$access_token,3600);
        }
        return $access_token;
    }

    //整合GET提交和POST提交
    public static function send($request_url, $data = [] ,$method = 'GET'){
        if( $method == "POST") {
            $result = curl_post_raw($request_url,$data);
        }else{
            $result = curl_get($request_url);
        }
        $wxResult = json_decode($result,true);  //true为数组，false为对象
        var_dump($wxResult);
        if(empty($wxResult)) {
            throw new Exception('获取access_token异常，微信内部错误');
        }else{
            $loginFail = array_key_exists('errcode',$wxResult);
            if($loginFail){
               return json(array(
                   'msg' => $wxResult['errmsg'],
                   'errorCode' => $wxResult['errcode'],
               ));
            }
        }
        return $wxResult;
    }
}